<template>
    <div id="risk-order-content" class="order-content">
        <el-row class="risk-order-top">
            <el-col :span="12" class="form-col col-box">
                <el-row class="form-content">
                    <ExchangeOrder
                        class="echange"
                        v-if="type == '6'"
                        :key="renderCountKey"
                        :renderCount="renderCountKey"
                        :detail="detail"
                        :notMesh="notMesh"
                        @handleSettingValue="handleSettingValue(arguments)"
                        @getStockInfo="getStockInfo(arguments)"
                    />

                    <BankZQ
                        class="bankbBond"
                        v-if="type == '2'"
                        :renderCount="renderCountKey"
                        :key="renderCountKey"
                        :detail="detail"
                        :notMesh="notMesh"
                        @handleSettingValue="handleSettingValue(arguments)"
                        @getStockInfo="getStockInfo(arguments)"
                    />
                    <RefinancingRiskOrder
                        class="refinance"
                        v-if="type == '14'"
                        :key="renderCountKey"
                        :renderCount="renderCountKey"
                        :detail="detail"
                        :notMesh="notMesh"
                        :tableSelectedRefinancingInfo="tableSelectedRefinancingInfo"
                        @handleSettingValue="handleSettingValue(arguments)"
                        @getStockInfo="getStockInfo(arguments)"
                        @resetTableSelected="resetTableSelected"
                    ></RefinancingRiskOrder>
                </el-row>
                <el-row class="form-operate">
                    <el-col :span="7">
                        <i style="font-size: 25px" name="entrySetting" class="el-icon-setting iconClass" @click="openEntryGroup"></i>
                    </el-col>
                    <el-col :span="17" style="padding-left: 10px">
                        <el-button size="mini" name="重置" @click="handleResetForm">重置</el-button>
                        <el-button type="primary" name="试算" @click="test" size="mini">试算</el-button>
                        <el-button type="primary" name="下单" @click="handlePlaceOrderClick" size="mini">下单</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="12" class="col-box">
                <el-tabs type="card" v-model="activePane">
                    <el-tab-pane label="产品持仓信息" name="1" v-if="['2', '6'].includes(type)">
                        <risk-table
                            class="position"
                            :msg="fundPositionsListMsg"
                            @getList="getFundPositionList"
                            @handleFilter="handleFilterFundPosition"
                        ></risk-table>
                    </el-tab-pane>
                    <el-tab-pane label="在途转融通" name="1" v-if="['14'].includes(type)">
                        <risk-table
                            class="position"
                            :msg="fundPositionsListMsg"
                            @getList="getFundPositionList"
                            @handleDbRow="handleDbRow"
                        ></risk-table>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>
        <el-row class="risk-order-bottom">
            <el-col class="col-box">
                <h3>
                    <el-row class="result-span">
                        <el-col :span="3">
                            <span>风控结果:</span>
                            <status-tag :code="riskResult"></status-tag>
                        </el-col>
                        <el-col :span="6">
                            <span>试算/下单时间: </span>
                            <span style="color: red">{{ calcTime }}</span>
                        </el-col>
                        <el-col :span="5">
                            <span>计算耗时: </span>
                            <span style="color: red">{{ takeTime }}</span>
                        </el-col>
                        <el-col :span="6">
                            <span>条目检查数:</span>
                            <span v-show="riskResultTable.length" style="color: red">{{ this.riskResultTable.length }}</span>
                        </el-col>
                        <el-col :span="4">
                            <el-button style="float: right" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                            <!-- <el-checkbox v-model="thresholdTypeFilter['1']" @change="handelThresholdTypeFilter('1')">显示触警</el-checkbox>
                            <el-checkbox v-model="thresholdTypeFilter['0']" @change="handelThresholdTypeFilter('0')">显示合规</el-checkbox> -->
                        </el-col>
                    </el-row>
                </h3>
                <div style="height: calc(100% - 40px)">
                    <vxe-table
                        :key="tableKey"
                        :auto-resize="true"
                        :data="riskResultTable"
                        border
                        size="mini"
                        style="width: 100%"
                        height="100%"
                        v-loading="calcLoading"
                        resizable
                        :resizable-config="{ minWidth: '60' }"
                        show-header-overflow
                        :sort-config="{ defaultSort: { field: 'thresholdType', order: 'desc' }, sortMethod: customSortMethod }"
                        header-align="center"
                        :cell-style="getCellStyle"
                    >
                        <vxe-column
                            v-for="(item, index) in showFieldList"
                            :key="index + item.id"
                            :field="item.id"
                            :title="item.content"
                            :sortable="item.sortable"
                            :column-config="{ isHover: true }"
                            :row-config="{ isHover: true }"
                            :filters="item.filters"
                            :filter-method="item.filterMethod"
                            :filter-render="{ name: 'FilterInput' }"
                            show-overflow
                            min-width="120"
                        >
                            <template
                                #filter="{ $panel, column }"
                                v-if="
                                    [
                                        'fundCode',
                                        'fundNameSt',
                                        'assetCode',
                                        'assetName',
                                        'fundAccountCode',
                                        'fundAccountName',
                                        'stockCode',
                                        'stockNameSt',
                                        'entryCode',
                                        'entryName',
                                    ].includes(item.id)
                                "
                            >
                                <div>
                                    <el-input
                                        v-focus
                                        ref="searchInput"
                                        class="my-input"
                                        type="type"
                                        v-for="(option, index) in column.filters"
                                        :key="index"
                                        v-model="option.data"
                                        @input="$panel.changeOption($event, !!option.data, option)"
                                    />
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="item.id === 'entryType'">{{ entryType[scope.row.entryType] }}</span>
                                <span v-else-if="item.id === 'compareType'">{{ compareDirection[scope.row.compareType] }}</span>
                                <status-tag v-else-if="item.id === 'thresholdType'" :code="scope.row.thresholdType" />
                                <branch-tag v-else-if="item.id === 'branchNum'" :data="scope.row" />
                                <span v-else-if="['investableBalance', 'maxTradable', 'maxTradableMerge'].includes(item.id)">
                                    <el-popover
                                        v-if="getObjectLength(scope.row[item.id]) && getObjectLength(scope.row[item.id]) > 1"
                                        placement="top"
                                        trigger="hover"
                                    >
                                        <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row[item.id]" :key="key">
                                            {{ '阀值' + ++index + getShowName(item.id) + ': ' + scope.row[item.id][getParamName(item.id) + index] }}
                                        </div>
                                        <el-tag slot="reference">{{ getObjectLength(scope.row[item.id]) + '个' + getShowName(item.id) }}</el-tag>
                                    </el-popover>
                                    <span
                                        v-else-if="getObjectLength(scope.row[item.id])"
                                        v-for="(value, key) in scope.row[item.id]"
                                        :key="key"
                                        style="float: right"
                                        >{{ value }}</span
                                    >
                                    <span v-else style="float: right"> --</span>
                                </span>
                                <span v-else-if="item.id === 'thresholdValue'" style="float: right">{{
                                    scope.row[item.id] != undefined
                                        ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit)
                                        : '--'
                                }}</span>

                                <span v-else-if="item.id === 'calculateValue'" style="float: right">
                                    {{
                                        scope.row[item.id] != undefined
                                            ? numberFormat(scope.row[item.id], !scope.row.unit || scope.row.unit == '无' ? 2 : scope.row.unit) +
                                              unitShow(scope.row.unit)
                                            : '--'
                                    }}
                                </span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </el-col>
        </el-row>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="getTableName(type)"
            @on-submit="onSubmit"
        />

        <EntryGroupSetting
            v-if="transDialog"
            :resourceCode="resourceCode"
            :transDialog="transDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />

        <!--处理下单后的弹窗-->
        <RiskOrderResultAfter
            v-if="orderCancelShow"
            :key="riskOrderResultAfterKey"
            :riskResultThresholdType="result"
            :res="riskOrderResultTable"
            @riskResultContinue="riskResultContinue"
            @riskResultCancel="riskResultCancel"
        />
    </div>
</template>
<script lang="ts">
import { UUID, numberFormat, unitShow, dateFormat, sortBy, getConfigItem } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import ExchangeOrder from '../components/exchange-order.vue';
import BankZQ from '../components/bank-zq.vue';
import RiskOrderResultAfter from './risk-order-result-after.vue';
import Invest from '@/common/dict/invest';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { getActiveMenuCode, getUser } from '@/utils/user-util';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskTable from '@/common/components/risk-table.vue';
import ColumnUtil from '../utils/column-util';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import { getSystemTradeDay } from '../api';
import VXETable from 'vxe-table';
import { trialCalculate, cancelCommonOrder } from '@/common/api/instruction';
import EntryGroupSetting from '../components/entry-group-seting.vue';
import RefinancingRiskOrder from '../refinancing/refinancing-risk-order.vue';

// 创建一个简单的输入框筛选
VXETable.renderer.add('FilterInput', {
    // 筛选模板
    // renderFilter(h, renderOpts, params) {
    //     return [`<filter-input params=${params}></filter-input>`];
    // },
    // 重置数据方法
    filterResetMethod({ options }) {
        options.forEach(option => {
            option.data = '';
        });
    },
    // 重置筛选复原方法（当未点击确认时，该选项将被恢复为默认值）
    filterRecoverMethod({ option }) {
        option.data = '';
    },
    // 筛选方法
    filterMethod({ option, row, column }) {
        const { data } = option;
        const cellValue = row[column.property];
        if (cellValue) {
            return cellValue.indexOf(data) > -1;
        }
        return false;
    },
});
// 筛选指令获取焦点
Vue.directive('focus', {
    inserted(el, binding, vnode) {
        el.querySelector('input').focus();
    },
});
// 交易所指令、银行间债券指令、存款指令风险下单Tab
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'RiskOrder',
    components: {
        ExchangeOrder,
        BankZQ,
        RiskTableLayout,
        RiskTable,
        StatusTag,
        BranchTag,
        RiskOrderResultAfter,
        EntryGroupSetting,
        RefinancingRiskOrder,
    },
})
export default class RiskOrder extends Vue {
    dateFormat = dateFormat;
    numberFormat = numberFormat;
    unitShow = unitShow;
    @Prop()
    detail: any;
    @Prop()
    type: any;
    ColumnUtil = new ColumnUtil();
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    // 是否修改
    isUpdate: boolean = false;
    oldOuterOrderCode: string = '';
    serialNo: string = '';

    // 下单类型转换
    InstTypePojo = {
        '1': '1',
        '2': '1',
        '3': '2',
        '4': '2',
        '5': '3',
        '6': '1',
        '7': '6',
        '8': '8',
        '14': '14',
    };

    Invest: any = new Invest();
    // 显示的标签页
    activePane: string = '1';

    notMesh: boolean = true; // 是否为单独页面

    cancelOrder: any = {
        cancelOrderType: '2',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };

    // 风控结果表数据
    riskResultTable: any[] = [];
    riskOrderResultTable: any[] = [];

    // 条目组穿梭框
    transDialog: boolean = false;
    layoutDialog: boolean = false;

    // 右侧双击表格行
    tableSelectedRefinancingInfo: any = null;
    // 产品持仓信息相关
    fundPositionsListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: [],
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 全部表格列
    tableColumns: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: false },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
        { content: '证券代码', id: 'stockCode', sortable: true },
        { content: '证券名称', id: 'stockNameSt', sortable: false },
        { content: '条目编号', id: 'entryCode', sortable: true },
        { content: '委托方向', id: 'orderDirection', sortable: false },
        { content: '风险说明', id: 'entryName', sortable: false },
        { content: '风险类型', id: 'entryType', sortable: false },
        { content: '风控阈值', id: 'thresholdValue', sortable: false },
        { content: '比较方向', id: 'compareType', sortable: false },
        { content: '计算结果(单位)', id: 'calculateValue', sortable: false },
        { content: '阈值类型', id: 'thresholdType', sortable: true },
        { content: '可投余量', id: 'investableBalance', sortable: false },
        { content: '最大可交易量', id: 'maxTradable', sortable: false },
        { content: '最大可交易量(汇总)', id: 'maxTradableMerge', sortable: false },
        { content: '静态条目KEY', id: 'entryKey', sortable: false },
        { content: '分支详情', id: 'branchNum', sortable: false },
    ];

    // 要显示的表格列
    showFieldList: any[] = [];
    // 已选择字段列表
    selectedFieldList: any[] = [];
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];
    // 风险类型
    entryTypeArr: any[] = [];
    // 阈值类型
    ThresholdTypeArr: any[] = [];

    // 图标dom
    iconDom: any = null;
    tableKey: number = 0;
    calcLoading: boolean = false;

    instruction: any = {};
    instructionCache: any = {};
    stockInfoCache: any = {};
    stockInfo: any = {};
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    marketCodePojo: any = {};
    OrderDirection: any = {};

    calcTime: string = ''; // 下单/试算时间
    takeTime: string | number = ''; // 计算耗时
    riskResult: string | number = ''; // 风控结果

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    stockInfoPojo: any = {};
    renderCountKey: number = 0;

    selectEntryGroupCode = {
        calculateEntryGroup: [],
        excludeEntryGroup: [],
    };

    // 分页
    pages = { currentPage: 1, pageSize: 25 };
    verInt: boolean = false;

    // 是否下单
    isPlaceOrder: boolean = false;
    form: any = {};
    result: string = '';
    tradeDays: any[] = []; // 交易日
    url: string = '';
    fundFilterList: any[] = [];

    // 过滤条件
    stockCode1: string = '';
    stockName1: string = '';

    orderCancelShow: boolean = false;
    riskOrderResultAfterKey: number = 0;

    originOuterOrderCode: string = '';
    resourceCode: string = ''; // 当前菜单字段编码

    async mounted() {
        this.tableColumns = this.ColumnUtil.handleResultColumns(this.tableColumns, 'id');
        this.resourceCode = getActiveMenuCode().defaultActive;
        this.getUserSelectEntryGroupList();
        getSystemTradeDay().then(res => {
            this.tradeDays = res.map(item => Number(item)).sort((a, b) => a - b);
        });
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        this.queryLayout();
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;

        this.marketCodePojo = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());
        this.OrderDirection = DictionConstUtil.ListToPojo(await DictionConstUtil.FNTradeDirection());
    }

    // 指令事件回调
    handleSettingValue(msg: any) {
        let data = JSON.parse(JSON.stringify(msg[0]));
        this.instructionCache = data;
    }

    // 证券信息回调
    getStockInfo(args: any) {
        this.stockInfo = args[0];
        this.stockInfoCache = this.stockInfo || {};
    }

    @Watch('instructionCache.fundCode', { immediate: true, deep: true })
    onWatchFundCode(newValue, oldValue) {
        if (newValue != oldValue && this.instructionCache.fundCode) {
            this.getFundPositionList(this.pages);
        }
    }

    @Watch('instructionCache.fundAccountCode', { immediate: true, deep: true })
    onWatchFundAcCode(newValue, oldValue) {
        if (newValue != oldValue && this.instructionCache.fundAccountCode) {
            this.getFundPositionList(this.pages);
        }
    }

    @Watch('type', { immediate: true })
    onWatchType() {
        this.url = '';
        if (['6', '2'].includes(this.type)) {
            // 交易所
            this.url = 'position/stock';
            this.fundPositionsListMsg.title = this.ColumnUtil.proPositionColumns;
        } else if (this.type == '14') {
            this.url = 'position/stock';
            this.fundPositionsListMsg.title = this.ColumnUtil.refinancingPositionColumns;
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    onWatchDetail(newData, oldData) {
        if (JSON.stringify(newData) !== JSON.stringify(oldData)) {
            if (this.detail?.instNo) {
                this.isUpdate = true;
                this.oldOuterOrderCode = this.detail.outerOrderCode;
                this.serialNo = this.detail.serialNo;
                this.cancelOrder.instNo = this.detail.instNo;
                this.cancelOrder.originOuterOrderCode = this.detail.outerOrderCode;
                this.renderCountKey++;
            } else {
                this.isUpdate = false;
            }
        }
    }

    // 重置按钮事件
    handleResetForm() {
        this.renderCountKey++;
        this.$emit('reset', null);
        this.fundPositionsListMsg.returnData.data = [];
        this.fundPositionsListMsg.returnData.total = 0;
    }

    // 产品持仓信息分页
    getFundPositionList(pages: any) {
        let form: any = {};

        let businessType = '';
        if (['6', '2', '14'].includes(this.type)) {
            if (this.type === '2') {
                // 银行间回购
                businessType = '2';
            } else {
                // 交易所、转融通
                businessType = '1';
            }

            // 判断是否带过滤条件
            if (!this.fundFilterList.length) {
                form = {
                    businessType: businessType,
                    fundCode: [this.instructionCache.fundCode],
                    fundAcCode: [this.instructionCache.fundAccountCode],
                    paging: pages,
                };
            } else {
                form = {
                    businessType: businessType,
                    stockCode: this.stockCode1,
                    stockNameSt: this.stockName1,
                    fundCode: [this.instructionCache.fundCode],
                    fundAcCode: [this.instructionCache.fundAccountCode],
                    paging: pages,
                };
            }

            if (this.type == '14') {
                form.refinancing = true;
            }
        }

        // 获取产品持仓信息
        this.$axios
            .post(this.url, form)
            .then((res: any) => {
                this.fundPositionsListMsg.returnData.data = res.list;
                this.fundPositionsListMsg.returnData.total = res.total;
            })
            .catch(() => {});
    }

    // 双击右侧表格
    handleDbRow($event) {
        this.tableSelectedRefinancingInfo = $event.row;
    }

    resetTableSelected() {
        this.tableSelectedRefinancingInfo = null;
    }

    handleFilterFundPosition(filterList: any) {
        this.fundFilterList = filterList;
        this.stockCode1 = '';
        this.stockName1 = '';
        if (filterList.length) {
            let code = filterList.find(ele => ele.property === 'stockCode');
            let name = filterList.find(ele => ele.property === 'stockNameSt');
            this.stockCode1 = code?.datas[0] || '';
            this.stockName1 = name?.datas[0] || '';
        }
        this.getFundPositionList(this.pages);
    }

    /**
     * 获取交易所指令的表单验证参数
     */
    getExChangeOrderVerify(instruction, stockInfo) {
        let verify = {
            fundCode: '产品代码',
            fundAccountCode: '组合编码',
            reportCode: '证券代码',
            orderDirection: '委托方向',
        };
        let extraField: any = {};
        if (instruction.showType === 1) {
            extraField = {
                // orderPrice: '指令价格',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
            if (stockInfo.stockType === 'a') {
                // 股票申购
                extraField.winningRate = '预估中签率';
            }
        } else if (instruction.showType === 2) {
            // 转融通//
            extraField = {
                deadline: '期限',
                rate: '费率',
                // counterparty:'交易对手',
                businessType: '业务类型',
                orderAmount: '融出数量',
            };
        } else if (instruction.showType === 3) {
            extraField = {};
            if (stockInfo.stockType === 'k') {
                // 债券申购
                extraField.winningRate = '预估中签率';
            }
            if (stockInfo.quoteType === '1') {
                // 是否净价
                // extraField.netPrice = '净价'
                extraField.orderAmount = '指令数量';
                extraField.netMoney = '指令金额';
            } else {
                // extraField.allPrice='全价价格'
                extraField.orderAmount = '全价数量';
                extraField.allMoney = '全价金额';
            }
        } else if (instruction.showType === 4 || instruction.showType === 5) {
            extraField = {
                // orderPrice: '指令价格',
                orderAmount: '指令数量',
                orderBalance: '指令金额',
            };
        } else if (instruction.showType === 6) {
            extraField = {
                orderRate: '回购利率',
                orderBalance: '指令金额',
            };
        } else if (instruction.showType === 8) {
            extraField = {
                orderPrice: '净价价格',
                fullPrice: '全价价格',
                orderAmount: '指令数量',
                orderBalance: '净价金额',
                totalInterest: '总应计利息',
                fullBalance: '全价金额',
                yield: '到期收益率',
                opponentCode: '交易对手',
            };
        }

        return { ...verify, ...extraField };
    }

    // 校验指令信息
    verifyInstructionParam(instruction, stockInfo) {
        console.log(instruction.instType, 'jjjjjjjjjjjjjjjj');

        let verify: any = {};
        if (!instruction) {
            this.yh_message_warn(' 请完善指令信息!');
            return false;
        }

        if (instruction.instType === '14') {
            console.log(instruction, 'instruction');
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                stockCode: '证券代码',
                orderDirection: '委托方向',
                deadline: '期限',
                rate: '费率',
                opponentCode: '交易对手',
                businessType: '业务类型',
                orderAmount: instruction.orderDirection == 'l' ? '融出数量' : instruction.orderDirection == '98' ? '了结数量' : '展期数量',
            };
            if (instruction.orderDirection == '98' && !instruction.advanceSettleDate) {
                this.yh_message_warn('提前了结日期不可为空');
                return false;
            } else if (['M', '98'].includes(instruction.orderDirection) && !instruction.originDealNo) {
                this.yh_message_warn('合约编号不可为空');
                return false;
            }
        } else if (instruction.instType === '6') {
            verify = this.getExChangeOrderVerify(instruction, stockInfo);
            if (instruction.orderBalance !== undefined && Number(instruction.orderBalance).toFixed(2).length > 16) {
                this.yh_message_warn('指令金额不能超过16位');
                return false;
            }
        } else if (instruction.instType === '2') {
            console.log(instruction, 'instruction2222');
            verify = {
                fundCode: '产品代码',
                fundAccountCode: '组合编码',
                reportCode: '证券代码',
                orderDirection: '委托方向',
                clearSpeed: '清算速度',
                orderPrice: '净价价格',
                fullPrice: '全价价格',
                orderBalance: '净价金额',
                stockFaceBalance: '券面总额',
                firstSettleDate: '结算日期',
                totalInterest: '总应计利息',
                settlementBalance: '结算金额',
                opponentCode: '交易对手',
            };
        }
        for (let key in verify) {
            // 费率允许为0
            if (!instruction[key] && key !== 'orderPriceType' && key !== 'rate') {
                this.yh_message_warn(verify[key] + ' 不可为空');
                return false;
            }
        }
        return true;
    }

    // 组装指令信息
    createInstruction(instruction, stockInfo) {
        instruction.requestId = UUID() + '-' + new Date().getTime();
        instruction.outerOrderCode = instruction.requestId;
        instruction.orderUser = getUser().userCode;
        instruction.orderPurpose = '15';

        if (instruction.instType !== '7') {
            // instruction.investType = 'a';
            instruction.investType = '1';
        }
        instruction.orderLevel = '0';
        instruction.remark = ' ';
        instruction.instructionType = this.InstTypePojo[instruction.instType];
        if (instruction.instType == '14') {
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = instruction.businessType;
            instruction.instructionTypeName = instruction.businessType;
            instruction.instructionType = '14'; //
        } else if (instruction.instType === '6') {
            // 交易所指令
            if (!instruction.exchangeType) {
                instruction.exchangeType = instruction.showType;
            }
            instruction.marketCode = stockInfo.marketCode;
            instruction.businClass = instruction.businessType;
            instruction.instructionType = '4';
            instruction.instructionTypeName = instruction.businessType;
            if (instruction.showType == 2) {
                // instruction.instructionType = '14';
                instruction.instructionType = '4';
            } else if (instruction.showType == 3) {
                if (stockInfo.quoteType === '1') {
                    instruction.orderPrice = instruction.netPrice;
                    instruction.orderBalance = instruction.netMoney;
                } else {
                    instruction.orderPrice = instruction.allPrice;
                    instruction.orderBalance = instruction.allMoney;
                }
            } else if (instruction.showType == 6) {
                instruction.orderAmount = 0;
                instruction.orderPrice = instruction.orderRate;
                // instruction.instructionType = '2'
                instruction.instructionType = '4';
            }
        } else if (instruction.instType === '2') {
            // 银行间债券
            instruction.orderPriceType = '1';
            let amount = Number(instruction.stockFaceBalance) / Number(stockInfo.facePrice);
            instruction.orderAmount = amount === Infinity ? 0 : amount;
            instruction.marketCode = stockInfo.marketCode || instruction.marketCode;
            instruction.instructionType = '1';
            instruction.businClass = instruction.businessType;
            instruction.instructionTypeName = instruction.businessType;
            instruction.interest = instruction.totalInterest;
            instruction.mutureDate = instruction.firstSettleDate;
        }
        return instruction;
    }

    // 试算
    handlecCalculate(orderType: string) {
        const isUpdate = this.isUpdate;

        let instruction = JSON.parse(JSON.stringify(this.instructionCache || {}));
        let stockInfo = this.stockInfoCache || {};
        instruction.instType = this.type;

        if (!instruction) {
            this.yh_message_warn('请填写相关信息');
            return;
        }
        this.verInt = this.verifyInstructionParam(instruction, stockInfo);
        if (!this.verInt) {
            return;
        }

        instruction = this.createInstruction(instruction, stockInfo);
        instruction.orderType = orderType;
        instruction.orderPrice = instruction.orderPrice ? instruction.orderPrice : '0';
        instruction.rate = instruction.rate / 100;

        this.calcLoading = true;
        let start = window.performance.now();

        // 获取当前提交时间 (试算/下单时间)
        // 补零
        let fillZero = n => {
            let result = n.toString().length === 1 ? '0' + n : n;
            return result;
        };
        // 时间戳转换 yyyy-MM-dd
        let formatTime = (t = new Date()) => {
            let d = new Date(t);
            let year = d.getFullYear();
            let month = d.getMonth() + 1;
            let date = d.getDate();
            let hours = d.getHours();
            let minutes = d.getMinutes();
            let seconds = d.getSeconds();
            let result = `${year}-${fillZero(month)}-${fillZero(date)} ${fillZero(hours)}:${fillZero(minutes)}:${fillZero(seconds)}`;
            return result;
        };
        this.calcTime = formatTime(new Date());
        let instructionList = [];
        instructionList.push(instruction);
        console.log('instructionList', instruction);
        // 试算表单
        let calcForm: any = {
            orderType: orderType,
            multiType: '2',
            requestId: instruction.requestId,
            instructionType: instruction.showType == '6' ? '4' : this.InstTypePojo[instruction.instType],
            outOrderBatchCode: UUID() + new Date().getTime(),
            tradeUser: getUser().userCode,
            calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
            excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
            instList: instructionList,
        };

        if (orderType == '2') {
            this.instruction.cancelType = '1';
            calcForm.cancelType = '1';
        }
        if (isUpdate) {
            calcForm.excludeSerialNoSet = [this.serialNo];
        }
        this.originOuterOrderCode = instruction.outerOrderCode;

        trialCalculate(calcForm)
            .then(resList => {
                if (resList) {
                    // 风控结果
                    this.riskResult = resList.thresholdType;
                    this.result = resList.thresholdType;

                    let end = window.performance.now();
                    // 计算耗时
                    this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
                    const h = this.$createElement;

                    if (!this.isPlaceOrder) {
                        this.yh_message_success('提交试算信息成功');
                    }

                    let stockInfo = this.stockInfoCache || {};
                    this.stockInfoPojo = JSON.parse(JSON.stringify(stockInfo));
                    let data = resList.resultList || [];
                    // 根据产品代码 匹配产品名称
                    data.forEach(ele => {
                        ele.requestId = resList.requestId;
                        if (!ele.stockCode || ele.stockCode === ' ') {
                            ele.stockCode = this.stockInfo.stockCode;
                        }

                        for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                            const item = this.fundCodeSelectData[i];
                            if (ele.fundCode === item.fundCode) {
                                ele.fundNameSt = item.fundNameSt;
                            }
                        }
                        ele.stockNameSt = this.stockInfoPojo.stockNameSt;
                    });
                    // childCalculateResults = childCalculateResults.filter(item => item.thresholdType != '4');
                    // childCalculateResults = childCalculateResults.sort(sortBy('thresholdType', 'desc'));

                    // 获取最高级的阈值类型
                    // this.riskResult = childCalculateResults[0]?.thresholdType || resList.thresholdType;
                    // this.result = childCalculateResults[0]?.thresholdType || resList.thresholdType;
                    this.riskOrderResultTable = JSON.parse(JSON.stringify(data));
                    this.riskResultTable = JSON.parse(JSON.stringify(this.riskOrderResultTable));
                    if (orderType === '2') {
                        if (this.result === '0') {
                            this.orderCancelShow = false;
                            this.calcLoading = false;
                            this.handleResetForm();
                            this.handleResetResult();
                            this.$message.success({
                                message: h('p', null, [
                                    h('span', null, '本次风控试算结果为'),
                                    h('span', { style: 'color: #70b603' }, '"合规"'),
                                    h('span', null, '，已下单成功'),
                                ]),
                                // offset: 300,
                                showClose: true,
                                customClass: 'messageStyle',
                            });
                            this.isUpdate = false;
                            if (isUpdate) {
                                this.handleUpdateCancel();
                            }
                        } else {
                            this.riskOrderResultAfterKey++;
                            this.orderCancelShow = true;
                        }
                        // if (isUpdate) {
                        //     this.handleUpdateCancel();
                        // }
                    } else {
                        this.orderCancelShow = false;
                        this.calcLoading = false;
                        this.riskResultTable = this.riskOrderResultTable;
                    }
                } else {
                    this.calcLoading = false;
                    this.handleResetResult();
                }
            })
            .catch(() => {
                this.calcLoading = false;
            });
    }

    // 清空试算结果
    handleResetResult() {
        this.riskResultTable = [];
        this.riskResult = '';
        this.calcTime = '';
        this.takeTime = '';
    }

    // 试算按钮点击
    test() {
        this.isPlaceOrder = false;
        this.orderCancelShow = false;
        this.handlecCalculate('1');
    }

    // 下单按钮点击
    handlePlaceOrderClick() {
        this.result = '';
        this.isPlaceOrder = true;
        this.handlecCalculate('2');
    }

    /* ************************ 表格处理相关start *************************** */

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }
    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:center';
        let obj = this.tableColumns.find(item => item.id == column.property);
        // let obj = this.ColumnUtil.riskTableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    customSortMethod({ data, sortList }) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode.match('.*[A-Z]+.*') || ele.entryCode.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode') {
                YHList.sort(this.compare('entryCode'));
                NoYHlist.sort(this.compare('entryCode'));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(sortBy(property, order));
            }
        }
        return list;
    }

    compare(property) {
        return function(a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        this.$nextTick(() => {
            (this.$refs.searchInput as any).focus();
            console.log(this.$refs.searchInput);
        });
        console.log(this.$refs.searchInput);

        const property = column['property'];
        return row[property].includes(option.data);
    }

    formatterCell({ cellValue }) {
        return cellValue || '--';
    }

    changeTable() {
        this.$nextTick(() => {
            let nodeName = [];
            let icon = [];
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < 8; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    /* ************************** 表格处理相关end ***************************** */

    /* **************************** 布局设置start ***************************** */
    // 获取页面布局信息
    async queryLayout() {
        this.calcLoading = true;
        let layoutUrl = '';
        if (this.type === '6') {
            layoutUrl = '/tableLayout/query/EXCHANGE_TRIAL_CALCULATE';
        } else if (this.type == '14') {
            layoutUrl = '/tableLayout/query/REFINACING_CALCULATE';
        } else {
            layoutUrl = '/tableLayout/query/BANK_BOND_CALCULATE';
        }
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios(layoutUrl)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);

            this.calcLoading = false;
        } else {
            this.selectedFieldList = this.tableColumns;

            this.showFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        this.showFieldList.forEach((ele: any) => {
            if (['fundCode', 'assetCode', 'fundAccountCode', 'stockCode', 'entryCode'].includes(ele.id)) {
                this.$set(ele, 'sortable', true);
            }
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                this.$set(ele, 'filters', [{ data: '' }]);
                this.$set(ele, 'search', true);
            }
            if (ele.id == 'entryType') {
                this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
                this.$set(ele, 'filters', this.entryTypeArr);
            }
            if (ele.id == 'thresholdType') {
                this.$set(ele, 'filterMethod', this.filterThresholdType);
                this.$set(ele, 'filters', this.ThresholdTypeArr);
            }

            // 重新渲染表格
            this.changeTable();
            this.tableKey++;
        });
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
        this.iconDom = null;
        this.changeTable();
        this.tableKey++;
    }

    // 处理选择结果返回
    riskResultContinue() {
        this.handleResetForm();
        this.calcLoading = false;
        this.riskResultTable = this.riskOrderResultTable;
        console.log(this.isUpdate, 'isUpdate');
        if (this.isUpdate) {
            this.handleUpdateCancel();
        }
        this.yh_message_success('指令下达成功');
        this.isUpdate = false;
    }

    // 取消
    riskResultCancel() {
        this.calcLoading = false;
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            originOuterOrderCode: this.originOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.originOuterOrderCode],
        }).then(res => {
            this.yh_message_success('已终止指令下达');
        });
    }

    // 修改指令撤单
    handleUpdateCancel() {
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.oldOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.oldOuterOrderCode],
        })
            .then(res => {})
            .catch(err => {
                this.yh_message_success(err);
            });
    }

    /* ************************** 布局设置end *******************************/

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroup() {
        this.transDialog = true;
    }

    getEntryGroup(value: any) {
        this.selectEntryGroupCode.calculateEntryGroup = value.calculateEntryGroup;
        this.selectEntryGroupCode.excludeEntryGroup = value.excludeEntryGroup;
    }

    closeEntryDialog() {
        this.transDialog = false;
        this.getUserSelectEntryGroupList();
    }

    getUserSelectEntryGroupList() {
        this.$axios.get('/entry/group/user/select/list/' + this.resourceCode).then((res: any) => {
            res = res || [];
            let selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
            this.selectEntryGroupCode.calculateEntryGroup = selectEntryGroupCode.calculateEntryGroup;
            this.selectEntryGroupCode.excludeEntryGroup = selectEntryGroupCode.excludeEntryGroup;
        });
    }

    // 获取页面布局名
    getTableName(type: string) {
        if (type == '6') {
            return 'EXCHANGE_TRIAL_CALCULATE';
        } else if (type == '14') {
            return 'REFINACING_CALCULATE';
        } else if (type == '2') {
            return 'BANK_BOND_CALCULATE';
        }
    }

    /* ************************************ 条目组设置end ********************************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/risk-order';
</style>
<style lang="scss">
.messageStyle {
    background-color: #ecf9e3;
    border-color: #ecf9e3;
    font-size: 18px;
    .el-icon-success {
        color: #67c23a;
    }
}
</style>
